package com.trs.publish.controller;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.validation.Valid;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.Errors;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PatchMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.trs.publish.aspect.Description;
import com.trs.publish.aspect.OperationDesc;
import com.trs.publish.domain.Role;
import com.trs.publish.domain.SearchParam;
import com.trs.publish.domain.User;
import com.trs.publish.service.RoleService;
import com.trs.publish.service.UserService;



/**
 * 用户管理
 * @author jia.haihong
 *
 *Hello
 */

@Controller
public class UserController{ 
	
	private static final Logger logger = LoggerFactory.getLogger(UserController.class);

	@Autowired 
	private UserService userService;
	
	@Autowired 
	private RoleService roleService;
	
	@RequestMapping(value = "/toUser")
    public ModelAndView toUser(ModelAndView mav) {
        mav.setViewName("user/list");
        return mav;
    } 
	
	@PatchMapping(value = "/user")
    @ResponseBody
    @OperationDesc(description = Description.search_user)
    public Object search(@RequestBody SearchParam searchParam) {
		String userName = searchParam.getUsername();
		String department = searchParam.getDepartment();
		String startTime = searchParam.getStartTime();
		String endTime = searchParam.getEndTime();
		
		//根据查询条件获取用户列表
		User user = new User();
		user.setUsername(userName);
		user.setDepartment(department);
		user.setStartTime(startTime);
		user.setEndTime(endTime);
		
		//mybatis分页
		PageHelper.startPage(searchParam);
		List<User> list = userService.getList(user);
		
		//获取资源分类的Map
		Map<String,String> roleMap = this.getRoleMap();
		//转换结果集中的catalog
		for(User u:list){
			String roles = u.getRole();
			StringBuffer rolenames = new StringBuffer();
			if(!StringUtils.isEmpty(roles)){
				for(String role:roles.split(",")){
					rolenames.append(roleMap.get(role)).append(",");
				}
				if(StringUtils.isEmpty(rolenames)){
					u.setRole("");
				}else{
					u.setRole(rolenames.toString());
				}
			}
		}
		PageInfo<User> pageInfo = new PageInfo<User>(list);
        return pageInfo;
    }
	
	//获取所有的资源分类，并转换为map
	private Map<String, String> getRoleMap() {
		Map<String,String> map = new HashMap<String,String>();
		Role role = new Role();
		List<Role> list = roleService.getList(role);
		for(Role r:list){
			map.put(r.getRolename(),r.getMemo());
		}
		return map;
	}

	/**
	 * 删除用户
	 * 
	 * @param id
	 * @return
	 */
	@DeleteMapping(value="/user/{id}")
	@ResponseBody
	@OperationDesc(description = Description.delete_user)
	public Object delete(@PathVariable("id") long id) {
		Map<String, Object> map = new HashMap<String, Object>();
		logger.debug("删除用户id=" + id);
		userService.deleteUser(id);
		map.put("message", "删除用户成功！");
		return map;
	}
	
	/**
	 * 查询单个用户
	 * 
	 * @param userId
	 * @return
	 */
	@GetMapping(value = "/user/{id}")
	@OperationDesc(description = Description.get_user)
	public ModelAndView get(ModelAndView mav,@PathVariable("id") long id) {
		logger.debug("查询单个用户id=" + id);
		User user = new User();
		//获取用户信息
		if(id==0){
			user.setId(id);
		}else{
			user = userService.findById(id);
		}
		user.setPassword2("校验");
		//获取角色信息
		List<Role> roles = roleService.getAllRoles();
		mav.addObject("user", user);
		mav.addObject("roles", roles);
		mav.setViewName("user/detail");
		return mav;
	}
	
	/**
	 * 更新/新增用户
	 * 
	 * @param user
	 * @return
	 */
	@PostMapping(value = "/user")
	@OperationDesc(description = Description.addOrUpdate_user)
	public ModelAndView  addOrUpdate(ModelAndView model,@Valid User user, BindingResult result) {
		String role = user.getRole();
		
        if(!result.hasErrors()){  
        	//如果新添加用户，判断用户名是否已存在
 		   long id = user.getId();
 		   String message="";
 		   if(id == 0){
 				User u = userService.findByName(user.getUsername());
 				if (null != u) {
 					message="该用户名已存在。";
 				}
 			}
 		   if(StringUtils.isNotEmpty(message)) {
 			  model.addObject("MSG", message);
 		   }else {
 			  BCryptPasswordEncoder encode = new BCryptPasswordEncoder(4);
 			 
	 		  if(id == 0){//新增方法
					//重置id
					user.setId(null);
					//password加密
				    String hashPass = encode.encode(user.getPassword());
					user.setPassword(hashPass);
					user.setPassword2(hashPass);
					userService.save(user);
				}else{//修改方法
					//password加密
					//修改时如果密码未修改则不更新密码
					User u = userService.findById(id);
					if(user.getPassword().equals(u.getPassword())){
						user.setPassword(null);
					}else{
						 String hashPass = encode.encode(user.getPassword());
						user.setPassword(hashPass);
					}
					if(user.getRole()==null) {
						user.setRole("");
					}
					userService.update(user);
					model.addObject("user", userService.findById(id));
				}
	        	model.addObject("MSG", "提交成功！");
	 		   }
	        }
	    //获取角色信息
		List<Role> roles = roleService.getAllRoles();
		model.addObject("roles", roles);
	    model.setViewName("user/detail");     
		return model;
	}
}

